<template>
  <div class="container">
    <div class="filter-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            class="filter-item"
            v-model="filterText"
            placeholder="请输入机构名称"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            class="filter-item"
            v-model="filterUsable"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-col>
        <el-col :span="8" :offset="4" class="filter-btn-col">
          <el-button type="primary" icon="el-icon-search" @click="handleFilter"
            >查询</el-button
          >
          <el-button
            type="primary"
            v-permission="{ code: 'base:institutions:add' }"
            @click="addMechanism"
            >新增一级机构</el-button
          >
        </el-col>
      </el-row>
    </div>

    <el-tree
      :data="lists"
      :props="defaultProp"
      node-key="id"
      draggable
      ref="tree"
      v-loading="loading"
      default-expand-all
      @node-drop="handleDrop"
      :allow-drop="allowDrop"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :render-content="renderContent"
    >
    </el-tree>
    <!-- 新增模态窗 -->
    <el-dialog
      :title="(modalEdit ? '修改' : '新增') + '机构'"
      :visible.sync="dialogVisible"
      width="550px"
      center
      @closed="onDialogClose"
    >
      <div class="box">
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          label-position="left"
          label-width="120px"
        >
          <el-form-item label="上级机构" v-if="institutionName">
            <span v-text="detailInfo.deptName || detailInfo.deptName"></span>
          </el-form-item>
          <el-form-item label="机构名称" prop="deptName">
            <el-input :maxlength="30" v-model="form.deptName"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="usable">
            <el-select
              v-model="form.usable"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="机构编码" prop="deptCode">
            <el-input :maxlength="30" v-model="form.deptCode"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="deptDesc">
            <el-input
              type="textarea"
              :rows="3"
              v-model="form.deptDesc"
              placeholder="请输入描述"
              :maxlength="200"
              :show-word-limit="true"
              resize="none"
              :autosize="{ minRows: 3, maxRows: 5 }"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" v-db-click="'保存中...'" @click="saveForm"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dragTreeTable from "drag-tree-table";
import arrayToTree from "array-to-tree";
import {
  orderMechanism,
  addMechanism,
  deleteMechanism,
  updateMechanism,
  getMechanismList,
  currentPermission,
} from "@/api/resource";

export default {
  components: {
    // Pagination,
    dragTreeTable,
  },
  name: "AgencyMange",
  data() {
    return {
      form: {
        deptName: "",
        usable: 1,
        deptDesc: "",
        deptCode: "",
        //tenantId: this.sessionData("get", "tenantId"), // 当前租户id
      },
      filterText: "",
      filterUsable: "",
      addMenuLevel: 0,
      institutionName: true,
      listQuery: {
        deptName: "",
        usable: "",
        deptCode: "",
        //tenantId: this.sessionData("get", "tenantId"),
      },
      page: {
        pageSize: 10,
        pageNumber: 1,
        totalElements: 1,
      },
      modalEdit: false,
      dialogVisible: false,
      rules: {
        deptName: [{ required: true, message: "机构名称是必填的" }],
        usable: [{ required: true, message: "机构状态是必填的" }],
        deptCode: [{ required: true, message: "机构编码是必填的" }],
      },
      lists: [],
      defaultProp: {
        label: "deptName",
        id: "id",
        parentId: "parentId",
      },
      detailInfo: {},
      loading: true,
      parentId: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取机构数据
    getList() {
      getMechanismList(this.listQuery).then((res) => {
        this.lists = arrayToTree(res.data, {
          parentProperty: "parentId",
          customID: "id",
        });
        this.loading = false;
      });
    },
    // 处理筛选
    handleFilter() {
      this.$refs.tree.filter(this.filterText);
    },
    // 显示详情弹窗
    showDialogModal(row, edit) {
      this.modalEdit = edit;
      this.detailInfo = row;
      this.addMenuLevel = 1;
      this.institutionName = true;
      if (row.parentId == 0 && edit) this.addMenuLevel = 0;
      if (edit) {
        this.institutionName = false;
        this.form.deptDesc = row.deptDesc;
        this.form.deptName = row.deptName;
        this.form.usable = row.usable;
        this.form.deptCode = row.deptCode;
        this.form.id = row.id;
      }
      this.dialogVisible = true;
    },
    // 新增一级机构
    addMechanism() {
      this.addMenuLevel = 0;
      this.institutionName = false;
      this.dialogVisible = true;
      this.modalEdit = false;
    },
    // 提交表单
    saveForm() {
      let res = null;
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let params = {
            parentDeptDeep:
              (this.addMenuLevel && this.detailInfo.deptDeep) || 0,
            ...this.form,
            parentId: (this.addMenuLevel && this.detailInfo.id) || 0,
            //tenantId: this.sessionData("get", "tenantId"),
          };
          if (this.modalEdit) {
            delete params.parentDeptDeep;
            params.id = this.detailInfo.id;
            params.parentId = this.detailInfo.parentId;
            res = await updateMechanism(params);
          } else {
            res = await addMechanism(params);
          }
          if (res) {
            this.getList();
            this.$message({
              type: "success",
              message: "保存成功！",
            });
            this.dialogVisible = false;
          }
        } else {
          return false;
        }
      });
    },
    // 模态窗关闭事件
    onDialogClose() {
      this.$refs.form.resetFields();
      this.form = {
        deptName: "",
        usable: 1,
        deptDesc: "",
      };
    },
    filterNode(value, data) {
      if (typeof this.filterUsable !== "number" && this.filterText)
        return data.deptName.indexOf(this.filterText) !== -1;
      else if (!this.filterText && typeof this.filterUsable === "number")
        return data.usable === this.filterUsable;
      else if (!this.filterText && typeof this.filterUsable !== "number")
        return true;
      else
        return (
          data.name.indexOf(this.filterText) !== -1 &&
          data.usable === this.filterUsable
        );
    },
    // 判断是否允许放置
    allowDrop(draggingNode, dropNode, type) {
      // return draggingNode.leave === dropNode.leave;
      return draggingNode.data.parentId === dropNode.data.parentId;
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let params = {
        fid: draggingNode.data.id,
        sid: dropNode.data.id,
      };
      orderMechanism(params).then((res) => {
        this.getList();
      });
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          {!data.usable ? <s>{data.deptName}</s> : <span>{data.deptName}</span>}
          <span>
            <el-button
              type="text"
              v-permission={{ code: "base:institutions:add" }}
              size="mini"
              on-click={() => this.showDialogModal(data, false)}
            >
              新增下级机构
            </el-button>
            {data.operable ? (
              <span>
                <el-button
                  type="text"
                  size="mini"
                  v-permission={{ code: "base:institutions:update" }}
                  on-click={() =>
                    this.showDialogModal(
                      { parentName: node.parent.data.name, ...data },
                      true
                    )
                  }
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  v-permission={{ code: "base:institutions:delete" }}
                  on-click={() => {
                    this.$confirm("此操作将永久删除该菜单, 是否继续?", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    })
                      .then(() => {
                        deleteMechanism({ id: data.id }).then((res) => {
                          if (res.status == 200) {
                            this.$message({
                              type: "success",
                              message: "删除成功!",
                            });
                            this.getList();
                          } else {
                          }
                        });
                      })
                      .catch(() => {});
                  }}
                >
                  删除
                </el-button>
              </span>
            ) : null}
          </span>
        </span>
      );
    },
  },
  watch: {
    // filterText(val) {
    //   this.$refs.tree.filter(val);
    // },
    // filterUsable(val) {
    //   this.$refs.tree.filter(val);
    // },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}
.box {
  padding: 0 20px;
}
.filter-item {
  width: 100%;
}
.filter-btn-col {
  text-align: end;
}
::v-deep .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .el-button {
    margin-left: 15px;
  }
}
</style>